<template>
  <div>
    <el-form :inline="true" :model="dataForm">
      <el-form-item>
        <el-input
          v-model="dataForm.roleName"
          placeholder="角色名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button
          v-if="isAuth('sys:role:save')"
          type="primary"
          @click="addOrUpdateHandle()"
          >新增</el-button
        >
        <el-button
          v-if="isAuth('sys:role:delete')"
          type="danger"
          @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="15">
      <!--角色管理-->
      <el-col
        :xs="24"
        :sm="24"
        :md="16"
        :lg="16"
        :xl="17"
        style="margin-bottom: 10px"
      >
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
          </div>
          <el-table
            :data="dataList"
            v-loading="dataListLoading"
            @selection-change="selectionChangeHandle"
            @current-change="handleCurrentChange"
            highlight-current-row
          >
            <el-table-column type="selection" width="55"></el-table-column>

            <el-table-column
              prop="roleName"
              label="名称"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              prop="remark"
              label="描述"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="操作"
              width="130px"
              align="center"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button
                  v-if="isAuth('sys:role:update')"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="addOrUpdateHandle(scope.row.roleId)"
                ></el-button>
                <el-button
                  v-if="isAuth('sys:role:delete')"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteHandle(scope.row.roleId)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper"
          >
          </el-pagination>
          <!-- 弹窗, 新增 / 修改 -->
          <add-or-update
            v-if="addOrUpdateVisible"
            ref="addOrUpdate"
            @refreshDataList="getDataList"
          ></add-or-update>
        </el-card>
      </el-col>
      <!-- 角色菜单授权 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">菜单分配</span>
            <el-button
              v-if="isAuth('role:menu:update')"
              :disabled="!showButton"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu"
            >
              保存
            </el-button>
          </div>
          <el-tree
            ref="menu"
            node-key="menuId"
            lazy
            show-checkbox
            :data="menuList"
            :load="getMenuDatas"
            :props="defaultProps"
            accordion
            check-strictly
            :default-checked-keys="menuIds"
            @check="menuChange"
          >
          </el-tree>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import AddOrUpdate from './role-add-or-update'
export default {
  data() {
    return {
      defaultProps: { children: 'children', label: 'name', isLeaf: 'leaf' },
      dataForm: {
        roleName: ''
      },
      dataListLoading: false,
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      addOrUpdateVisible: false,
      dataListSelections: [],
      showButton: false,
      menuList: [],
      currentId: 0,
      menuIds: []
    }

  },
  components: {
    AddOrUpdate
  },
  activated() {
    this.getDataList();
  },
  methods: {
    getMenuDatas(node, resolve) {
      setTimeout(() => {
        //console.log(node);
        this.$http({
          url: this.$http.adornUrl('/sys/menu/tree'),
          method: 'get',
          params: this.$http.adornParams({
            'pid': node.data.menuId ? node.data.menuId : 0
          })
        }).then(({ data }) => {
          if (data && data.code === 0) {
            //console.log(data)
            resolve(data.menuTree)
          }
        })
      }, 100)

    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    //查找
    getDataList() {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/sys/role/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'roleName': this.dataForm.roleName
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    //删除
    deleteHandle(id) {
      var roleIds = id ? [id] : this.dataListSelections.map(item => {
        return item.roleId
      })
      this.$confirm(`确定进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/sys/role/delete'),
          method: 'post',
          data: this.$http.adornData(roleIds, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => { })
    },
    // 触发单选
    handleCurrentChange(val) {
      if (val) {
        const _this = this
        // 清空菜单的选中
        this.$refs.menu.setCheckedKeys([])
        // 保存当前的角色id
        this.currentId = val.roleId
        // 初始化默认选中的key
        this.menuIds = []
        //console.log(val);
        val.menuIds.forEach(function (data) {
          _this.menuIds.push(data)
        })

        this.showButton = true
      }
    },
    menuChange(menu) {
      //console.log(menu);
      // 获取该节点的所有子节点，id 包含自身
      this.$http({
        url: this.$http.adornUrl('/sys/menu/child'),
        method: 'get',
        params: this.$http.adornParams({
          'id': menu.menuId
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          // 判断是否在 menuIds 中，如果存在则删除，否则添加
          if (this.menuIds.indexOf(menu.menuId) !== -1) {
            for (let i = 0; i < data.childIds.length; i++) {
              const index = this.menuIds.indexOf(data.childIds[i])
              if (index !== -1) {
                this.menuIds.splice(index, 1)
              }
            }
          } else {
            for (let i = 0; i < data.childIds.length; i++) {
              const index = this.menuIds.indexOf(data.childIds[i])
              if (index === -1) {
                this.menuIds.push(data.childIds[i])
              }
            }
          }
          this.$refs.menu.setCheckedKeys(this.menuIds)
        }
      });
    },
    //保存菜单
    saveMenu() {
      const role = { roleId: this.currentId, menus: [] }
      // 得到已选中的 key 值
      this.menuIds.forEach(function (id) {
        const menu = id
        role.menus.push(menu)
      })
      //console.log(role);
      this.$http({
        url: this.$http.adornUrl('/sys/role/menu'),
        method: 'put',
        data: this.$http.adornData({
          'roleId': role.roleId,
          'menuIds': role.menus
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500
          })
          this.getDataList()
        }
      }).catch(err => {
        console.log(err.response.data.message)
      })
    }


  }
}
</script>

<style lang="scss" scoped>

.clearfix {
  &:after {
    visibility: hidden;
    display: block;
    font-size: 0;
    content: " ";
    clear: both;
    height: 0;
  }
}
.role-span {
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}
</style>